<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px">
      <el-form-item label="医院名称" prop="hospitalName">
        <el-input
          v-model="queryParams.hospitalName"
          placeholder="请输入医院名称"
          clearable
          style="width: 200px"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="所属地区" style="margin-right: 0">
        <region-select
          :value="{
            provinceId: queryParams.provinceId,
            cityId: queryParams.cityId,
            countyId: queryParams.countyId
          }"
          :show-label="false"
          @change="handleRegionChange"
          ref="regionSelect"
        />
      </el-form-item>

      <el-form-item style="margin-left: 10px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['management:hospitalarea:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['management:hospitalarea:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['management:hospitalarea:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['management:hospitalarea:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="areaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="院区名称" align="center" prop="areaName" />
      <el-table-column label="联系电话1" align="center" prop="phone1" />
      <el-table-column label="联系电话2" align="center" prop="phone2" />
      <el-table-column label="公交信息" align="center" prop="busInfo" />
      <el-table-column label="所属地区" align="center">
        <template slot-scope="scope">
          {{ scope.row.provinceName || '-' }}
          {{ scope.row.cityName ? '/' + scope.row.cityName : '' }}
          {{ scope.row.countyName ? '/' + scope.row.countyName : '' }}
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center">
        <template slot-scope="scope">
          {{ formatDetailAddress(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="地图坐标" align="center" prop="mapLocation" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['management:hospitalarea:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['management:hospitalarea:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改医院导航对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="院区名称" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入院区名称" />
        </el-form-item>
        <el-form-item label="联系电话1" prop="phone1">
          <el-input v-model="form.phone1" placeholder="请输入联系电话1" />
        </el-form-item>
        <el-form-item label="联系电话2" prop="phone2">
          <el-input v-model="form.phone2" placeholder="请输入联系电话2" />
        </el-form-item>
        <el-form-item label="公交信息" prop="busInfo">
          <el-input v-model="form.busInfo" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <!-- 地址选择 -->
        <region-select
          v-model="form.region"
          :show-label="true"
          ref="formRegionSelect"
          @change="handleFormRegionChange"
        />

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>

        <el-form-item label="地图坐标" prop="mapLocation">
          <el-input v-model="form.mapLocation" placeholder="请输入地图坐标" />
        </el-form-item>

        <el-divider content-position="center">楼层信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddFloorInfo">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteFloorInfo">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="floorInfoList" :row-class-name="rowFloorInfoIndex" @selection-change="handleFloorInfoSelectionChange" ref="floorInfo">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="楼层号" prop="floorNumber" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.floorNumber" placeholder="请输入楼层号" />
            </template>
          </el-table-column>
          <el-table-column label="楼层名称" prop="floorName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.floorName" placeholder="请输入楼层名称" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHospitalarea, getHospitalarea, delHospitalarea, addHospitalarea, updateHospitalarea } from "@/api/management/hospitalarea";
import RegionSelect from '@/components/RegionSelect';

export default {
  name: "HospitalArea",
  components: {
    RegionSelect
  },
  data() {
    // 地址选择校验
    const validateProvince = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择省份'));
      } else {
        // 如果选择了省份，清空后续选项
        if (this.form.region.cityId) {
          this.form.region.cityId = '';
          this.form.region.cityName = '';
        }
        if (this.form.region.countyId) {
          this.form.region.countyId = '';
          this.form.region.districtName = '';
        }
        if (this.form.region.townId) {
          this.form.region.townId = '';
          this.form.region.streetName = '';
        }
        callback();
      }
    };
    const validateCity = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择城市'));
      } else {
        // 如果选择了城市，清空后续选项
        if (this.form.region.countyId) {
          this.form.region.countyId = '';
          this.form.region.districtName = '';
        }
        if (this.form.region.townId) {
          this.form.region.townId = '';
          this.form.region.streetName = '';
        }
        callback();
      }
    };
    const validateDistrict = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择区县'));
      } else {
        // 如果选择了区县，清空街道
        if (this.form.region.townId) {
          this.form.region.townId = '';
          this.form.region.streetName = '';
        }
        callback();
      }
    };

    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedFloorInfo: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 医院导航表格数据
      areaList: [],
      // 楼层信息表格数据
      floorInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalName: null,
        provinceId: '',
        cityId: '',
        countyId: '',
        townId: '',
        provinceName: '',
        cityName: '',
        districtName: '',
        streetName: ''
      },
      // 表单参数
      form: {
        areaId: null,
        areaName: null,
        phone1: null,
        phone2: null,
        busInfo: null,
        address: null,
        mapLocation: null,
        region: {
          provinceId: '',
          cityId: '',
          countyId: '',
          townId: '',
          provinceName: '',
          cityName: '',
          districtName: '',
          streetName: ''
        }
      },
      // 表单校验
      rules: {
        areaName: [
          { required: true, message: "院区名称不能为空", trigger: "blur" }
        ],
        phone1: [
          { required: true, message: "联系电话1不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "详细地址不能为空", trigger: "blur" }
        ],
        'region.provinceId': [
          { required: true, validator: validateProvince, trigger: "change" }
        ],
        'region.cityId': [
          { required: true, validator: validateCity, trigger: "change" }
        ],
        'region.countyId': [
          { required: true, validator: validateDistrict, trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询医院导航列表 */
    getList() {
      this.loading = true;
      listHospitalarea(this.queryParams).then(response => {
        this.areaList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        areaId: null,
        areaName: null,
        phone1: null,
        phone2: null,
        busInfo: null,
        address: null,
        mapLocation: null,
        region: {
          provinceId: '',
          cityId: '',
          countyId: '',
          townId: '',
          provinceName: '',
          cityName: '',
          districtName: '',
          streetName: ''
        }
      };
      this.floorInfoList = [];
      this.resetForm("form");
      // 重置地址选择组件
      this.$refs.formRegionSelect && this.$refs.formRegionSelect.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;

      // 执行查询
      this.loading = true;
      listHospitalarea(this.queryParams).then(response => {
        this.areaList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 重置查询参数为初始状态
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        hospitalName: null,
        provinceId: '',
        cityId: '',
        countyId: '',
        townId: '',
        provinceName: '',
        cityName: '',
        districtName: '',
        streetName: ''
      };

      // 重置表单
      this.resetForm("queryForm");

      // 重置地址选择组件
      this.$refs.regionSelect && this.$refs.regionSelect.reset();

      // 重新查询数据
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.areaId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ path: '/management/hospitalarea/form' });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const areaId = row.areaId || this.ids;
      this.$router.push({ path: `/management/hospitalarea/form/${areaId}` });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保地区名称也被包含在提交数据中
          console.log('提交前的表单数据:', this.form);

          // 将地址信息合并到表单数据中
          const submitData = {
            ...this.form,
            provinceId: this.form.region.provinceId,
            cityId: this.form.region.cityId,
            countyId: this.form.region.countyId,
            townId: this.form.region.townId,
            provinceName: this.form.region.provinceName,
            cityName: this.form.region.cityName,
            districtName: this.form.region.districtName,
            streetName: this.form.region.streetName,
            floorInfoList: this.floorInfoList
          };

          console.log('最终提交的数据:', submitData);

          if (this.form.areaId != null) {
            updateHospitalarea(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHospitalarea(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const areaIds = row.areaId || this.ids;
      this.$modal.confirm('是否确认删除医院导航编号为"' + areaIds + '"的数据项？').then(function() {
        return delHospitalarea(areaIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 楼层信息序号 */
    rowFloorInfoIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 楼层信息添加按钮操作 */
    handleAddFloorInfo() {
      let obj = {};
      obj.floorNumber = "";
      obj.floorName = "";
      this.floorInfoList.push(obj);
    },
    /** 楼层信息删除按钮操作 */
    handleDeleteFloorInfo() {
      if (this.checkedFloorInfo.length == 0) {
        this.$modal.msgError("请先选择要删除的楼层信息数据");
      } else {
        const floorInfoList = this.floorInfoList;
        const checkedFloorInfo = this.checkedFloorInfo;
        this.floorInfoList = floorInfoList.filter(function(item) {
          return checkedFloorInfo.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleFloorInfoSelectionChange(selection) {
      this.checkedFloorInfo = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      // 定义要导出的字段列表
      const columns = [
        { index: 0, label: "院区名称", prop: "areaName" },
        { index: 1, label: "联系电话1", prop: "phone1" },
        { index: 2, label: "联系电话2", prop: "phone2" },
        { index: 3, label: "公交信息", prop: "busInfo" },
      ];

      this.download('management/hospitalarea/export', {
        ...this.queryParams,
        // 传递列配置
        exportColumns: JSON.stringify(columns)
      }, `hospitalarea_${new Date().getTime()}.xlsx`)
    },
    // 地址选择变化（查询表单）
    handleRegionChange(region) {
      // 添加日志帮助调试
      console.log('地址选择变化:', region);

      // 更新查询参数
      this.queryParams = {
        ...this.queryParams,
        provinceName: region.provinceName || '',
        cityName: region.cityName || '',
        districtName: region.districtName || ''
      };

      // 自动触发查询
      this.handleQuery();
    },
    // 表单地址选择变化
    handleFormRegionChange(region) {
      // 如果选择了新的省份，清空后续选项
      if (this.form.region.provinceId !== region.provinceId) {
        region.townId = '';
        region.streetName = '';
      }
      // 如果选择了新的城市，清空后续选项
      else if (this.form.region.cityId !== region.cityId) {
        region.countyId = '';
        region.districtName = '';
        region.townId = '';
        region.streetName = '';
      }

      this.form.region = region;
    },
    /** 格式化详细地址 */
    formatDetailAddress(row) {
      if (!row.address) return '';

      let address = row.address;
      const removeItems = [
        row.provinceName,
        row.cityName === '市辖区' ? '' : row.cityName,
        row.districtName
      ].filter(Boolean);

      return address || row.address;
    }
  }
};
</script>

<style lang="scss" scoped>
.el-form {
  .region-select {
    display: inline-block;
    margin-right: 0;

    :deep(.el-select) {
      width: 150px;
      margin-right: 8px;

      &:last-child {
        margin-right: 0;
      }
    }
  }
}

.el-dialog {
  .el-form {
    .region-select {
      display: block;
      margin-right: 0;
    }
  }
}

.mb8 {
  margin-bottom: 8px;
}

.el-form-item {
  margin-bottom: 8px;
}
</style>
